-- upgrade_ship
-- Created by chengb Jul/18/2015
-- 成就：升级幽灵船技能

-- 内部函数声明
local whenUpgradeShip;
local whenAttribBonus;
local checkComplete;

-- 注册幽灵船升级的回调
EventMgr.register("achievements/upgrade_ship", event.SHIP_LEVEL_UP, function(args)
    whenUpgradeShip(args);
end);

-- 注册获得属性奖励的回调
EventMgr.register("achievements/upgrade_ship", event.DO_BONUS, function(bonus)
    whenAttribBonus(bonus);
end);

-- 注册幽灵船升级的回调
whenUpgradeShip = function(args)
    local level = args.level;

    checkComplete(level);
end

-- 注册获得属性奖励的回调
whenAttribBonus = function(bonus)
    -- 如果不是幽灵水手奖励，就不用管了
    if bonus[1] ~= 2 or bonus[2] ~= "ship_level" then
        return;
    end

    if ME.user.ship then
        -- 有幽灵船才检查进度
        local level = ME.user.ship:getLevel();
        checkComplete(level);
    end
end

-- 检查成就完成
function checkComplete(level)
    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    local layer = DungeonM.currentLayer();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("upgrade_ship");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end

        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["level"]) == 'number' and
                level < ruleArg["level"] then
                -- 等级未达标
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local level   = ruleArg["level"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", level);

        return desc;
    end,
};